<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <el-form :inline="true" class="demo-form-inline filter">
      <div>
        <el-form-item label="预存日期">
          <el-date-picker v-model="alarmdate" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
          <!-- <el-date-picker v-model="listQuery.prestoragedate" clearable style="width: 149px!important" type="date"
            placeholder="请选预存日期" /> -->
        </el-form-item>
        <el-form-item label="客户名称">
          <el-select v-model="listQuery.fsiteNo" :disabled="this.$store.state.user.fsiteLevel == 3" clearable filterable
            placeholder="请选择客户名称">
            <el-option v-for="item in fsiteNoBelongOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="课题组">
          <el-select v-model="listQuery.ftaskno" class="filter-item" clearable placeholder="请选择课题组">
            <el-option v-for="item in tsTaskuserlist" :key="item.ftaskno" :label="item.ftaskname"
              :value="item.ftaskno" />
          </el-select>
        </el-form-item>
        <el-form-item label="单号">
          <el-input v-model="listQuery.fbillno" clearable class="filter-item" style="width: 200px"
            placeholder="请输入单号" />
        </el-form-item>
      </div>

      <el-form-item>
        <el-button :style="{ background: buttonColor.lookup, color: buttonColor.color }" round size="medium"
          class="filter-item" @click="handleFilter">查找</el-button>
      </el-form-item>
      <el-form-item>
        <el-button :style="{ background: buttonColor.add, color: buttonColor.color }" round size="medium"
          class="filter-item" @click="handleCreate()">添加</el-button>
      </el-form-item>
    </el-form>
    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :height="buttonColor.clientHeightTwo" :data="list" :header-cell-style="tableColor"
      stripe element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column :width="buttonColor.operationThree" align="center" label="操作" class-name="small-padding">
        <template slot-scope="scope">
          <div class="operationButton">
            <div :style="{ color: buttonColor.edit, cursor: 'pointer' }" @click="edit(scope.row)">
              <img src="../../../public/images/edit.png">
              编辑
            </div>
            <div v-if="scope.row.fstate === 0" :style="{ color: buttonColor.examine, cursor: 'pointer' }"
              @click="confirm(scope.row)">
              <img src="../../../public/images/examine.png">
              确认
            </div>
            <div v-else :style="{ color: buttonColor.examine, cursor: 'pointer' }">
              <img src="../../../public/images/examine.png">
              确认
            </div>
            <div v-if="scope.row.fstate === 0" :style="{ color: buttonColor.invalid, cursor: 'pointer' }" @click="handleDelete(scope.row)">
              <img src="../../../public/images/invalid.png">
              作废
            </div>
            <div v-else :style="{ color: buttonColor.invalid, cursor: 'pointer' }">
              <img src="../../../public/images/invalid.png">
              作废
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column :width="buttonColor.line" :index="indexMethod" align="center" label="序" type="index" />
      <el-table-column :width="buttonColor.date" align="left" label="预存日期" prop="fchargedate" />
      <el-table-column width="180" align="left" label="预存单号" prop="fbillno" />
      <el-table-column align="left" label="课题组名称" prop="ftaskname" />
      <el-table-column align="left" label="预存人员" prop="fsiteName" />
      <el-table-column align="left" label="预存金额(元)" prop="fchargeamt" />
      <el-table-column align="left" label="备注" prop="fexplanation" />
      <el-table-column align="left" :width="buttonColor.state" label="状态" prop="fstate">
        <template slot-scope="scope">
          <span :style="{ color: buttonColor.statedisable }" v-if="scope.row.fstate == 0">{{ scope.row.fstate |
              statusFilter
          }}</span>
          <span :style="{ color: buttonColor.statestart }" v-else-if="scope.row.fstate == 1">{{ scope.row.fstate | statusFilter }}</span>
          <span :style="{ color: buttonColor.refused }" v-else>{{ scope.row.fstate | statusFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column :width="buttonColor.date" align="left" label="确认日期" prop="fupddate" />
    </el-table>

    <!-- 添加或修改对话框 -->
    <el-dialog :close-on-click-modal="false" :visible.sync="dialogFormVisible" width="800px" top="2vh">
      <template slot="title">
        <div :style="titleColor">{{ textMap[dialogStatus] }}</div>
      </template>
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="90px">
        <el-row>
          <el-col :span="12">
            <el-form-item class="required" label="预存单号" prop="fbillno">
              <el-input :disabled="true" v-model="dataForm.fbillno" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="required" label="预存日期" prop="fchargedate">
              <el-date-picker :picker-options="disabledDate" v-model="dataForm.fchargedate" type="date"
                placeholder="请选择预存日期" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item class="required" label="所属团队" prop="fteamno">
              <el-select @change="fteamnoChange" v-model="dataForm.fteamno" clearable filterable placeholder="请选择团队">
                <el-option v-for="item in tsTeamlist" :key="item.fteamno" :label="item.fteamname"
                  :value="item.fteamno" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="required" label="所属课题组" prop="ftaskno">
              <el-select @change="ftasknoChange" v-model="dataForm.ftaskno" clearable filterable placeholder="请选择课题组">
                <el-option v-for="item in tsTaskuserlist" :key="item.ftaskno" :label="item.ftaskname"
                  :value="item.ftaskno" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="12">
            <el-form-item label="业务类型" prop="fchargetype">
              <el-select v-model="dataForm.fchargetype" clearable filterable placeholder="请选择存/取">
                <el-option v-for="item in fchargetypelist" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>-->
        <el-row>
          <el-col :span="12">
            <el-form-item class="required" label="预存人员" prop="fuseuser">
              <el-select v-model="dataForm.fuseuser" clearable filterable placeholder="请选择预存人员">
                <el-option v-for="item in fuseuserlist" :key="item.id" :label="item.username" :value="item.id.toString()"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="required" label="预存金额" prop="fchargeamt">
              <el-input v-model="dataForm.fchargeamt" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="fexplanation">
              <el-input v-model="dataForm.fexplanation" class="inputwidth" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="经办人员" prop="foperator" v-if="dialogStatus == 'update'">
              <el-select :disabled="true" v-model="dataForm.foperator" clearable filterable placeholder="请选择经办人员">
                <el-option v-for="item in foperatorlist" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="dialogStatus == 'update'">
            <el-form-item label="经办时间" prop="fupddate">
              <el-input :disabled="true" v-model="dataForm.fupddate" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div v-if="viewFlag" slot="footer" class="dialog-footer">
        <el-button round :style="{ background: buttonColor.cancel, color: buttonColor.colorone }"
          @click="dialogFormVisible = false">取消</el-button>
        <el-button round v-if="dialogStatus == 'create'"
          :style="{ background: buttonColor.confirm, color: buttonColor.color }" @click="createData">确定</el-button>
      </div>
      <div v-else slot="footer" class="dialog-footer">
        <el-button round :style="{ background: buttonColor.cancel, color: buttonColor.colorone }"
          @click="dialogFormVisible = false">取消</el-button>
        <el-button round v-if="dialogStatus == 'create'"
          :style="{ background: buttonColor.confirm, color: buttonColor.color }" @click="createData">确定</el-button>
        <el-button round v-else :style="{ background: buttonColor.confirm, color: buttonColor.color }"
          @click="updateData">确定
        </el-button>
      </div>
      </div>
    </el-dialog>
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />
  </div>
</template>

<style>
.button-margin {
  margin: 2px 0px;
}

.el-button+.el-button {
  margin-left: 1px
}

.inputwidth {
  width: 100% !important;
}

.inputwidth input {
  width: 100% !important;
}
</style>
<script>
import { getListArea } from '@/api/area'
import { cance, tcDailyaccountupdate, tcDailyaccountcreate, getFbillno, tsTeamlist, tsTaskuserlist, listtsTaskuser, tcDailyaccountlist } from '@/api/labOrder/prestore'
import { fsiteOptionsByLevel, statusUpdate } from '@/api/area'
import Pagination from '@/components/Pagination'
import moment from 'moment'
import { tableColor, titleColor, buttonColor } from '@/filters/index'

const statusMap = {
  0: '未确认',
  1: '已确认',
  2: '已作废'
}

export default {
  name: 'Prestore',
  components: {
    Pagination
  },
  filters: {
    statusFilter(type) {
      return statusMap[type]
    }
  },
  data() {
    return {
      foperatorlist: [], // 经办人员列表
      viewFlag: false,
      fsiteNoBelongOptions: [], // 客户列表
      buttonColor,
      list: null,
      total: 0,
      listLoading: true,
      alarmdate: '',//搜索时间
      disabledDate: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;  //如果没有后面的-8.64e7就是不可以选择今天的
        }
      },//日期时间选择器
      listQuery: {
        page: 1,
        limit: 20,
        fsiteNo: this.$store.state.user.fsiteNo,
        ftaskno: undefined, // 课题组
        fbillno: undefined, // 单号
        maxTime: undefined,
        minTime: undefined,
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      fbillno: "", //自动单号
      tsTeamlist: [], // 团队列表
      tsTaskuserlist: [], //课题组
      fuseuserlist: [], // 预存人员列表
      dataForm: {
        fsiteNo: undefined,
        fbillno: undefined, // 预存单号
        fchargedate: undefined, // 预存日期
        ftaskno: undefined, // 课题组编号
        fteamno: undefined, // 所属团队
        fuseuser: undefined, // 预存人员
        fchargeamt: undefined, // 预存金额
        fexplanation: undefined, // 备注
        foperator: this.$store.state.user.id, // 经办人员
        fupddate: undefined, // 经办时间
        fchargetype: 1, //1存2取
        fstate: 0,//1已确认 0 未确认
      },
      fchargetypelist: [{ label: "存", value: 1 }, { label: "取", value: 2 }],
      tableColor: tableColor,
      titleColor: titleColor,
      rules: { // 表单提交规则
        fbillno: [
          { required: true, message: '预存单号不能为空' },
        ],
        fchargedate: [
          { required: true, message: '预存日期不能为空' },
        ],
        fteamno: [
          { required: true, message: '所属团队不能为空' },
        ],
        ftaskno: [
          { required: true, message: '课题组不能为空' },
        ],
        fuseuser: [
          { required: true, message: '预存人员不能为空' },
        ],
        fchargeamt: [
          { required: true, message: '预存金额不能为空' },
        ],
      }
    }
  },
  created() {
    this.alarmdate = [this.parserDate(moment(new Date().setDate(1)).format('YYYY-MM-DD')), new Date()]
    this.tsTeamlists(); //团队列表
    this.getList();  //预存列表

    // 客户列表
    fsiteOptionsByLevel(3)
      .then(response => {
        this.fsiteNoBelongOptions = response.data.data.list
      })
      .catch(() => {
        this.fsiteNoBelongOptions = []
      })
      // 人员
      getListArea({ flag: 13, arg1: this.$store.state.user.fsiteNo })
        .then(response => {
          this.foperatorlist = response.data.data.list
        })
        .catch(() => {
          this.foperatorlist = []
        })

  },
  methods: {
    datetimeFormat(row, column) {
      const date = row[column.property]
      if (date === undefined || date === null) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD')
    },
    timeFormat(row, column) {
      const date = row[column.property]
      if (date === undefined || date === null) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },

    //团队列表
    tsTeamlists() {
      console.log("团队列表")
      tsTeamlist().then((response) => {
        console.log(response.data.data.list)
        this.tsTeamlist = response.data.data.list
      })
        .catch(() => {
        })
    },
    // 团队改变
    fteamnoChange(value){
      this.tsTaskuserlist = []
      this.fuseuserlist = []
      this.dataForm.ftaskno = ''
      this.dataForm.fuseuser = ''
      if(value){
        this.tsTaskuserlists(value)
      }
    },

    //课题组列表
    tsTaskuserlists(value) {
      console.log("课题组列表")
      tsTaskuserlist({fteamno:value,fsiteNo: this.$store.state.user.fsiteNo,limit: -1}).then((response) => {
        console.log(response.data.data.list)
        this.tsTaskuserlist = response.data.data.list
      })
        .catch(() => {
        })
    },
    // 课题组改变
    ftasknoChange(value){
      this.fuseuserlist = []
      this.dataForm.fuseuser = ''
      if(value){
        this.getListAreas(value)
      }
    },
    //人员列表
    getListAreas(value) {
      console.log("人员列表")
      listtsTaskuser({ ftaskno: value })
        .then(response => {
          console.log(response)
          this.fuseuserlist = response.data.data.list
        })
        .catch(() => {
          this.fuseuserlist = []
        })
    },
    //添加单号自动生成
    getFbillnos() {
      console.log("单号自动生成")
      getFbillno().then((response) => {
        console.log(response.data.data)
        this.dataForm.fbillno = response.data.data
      })
        .catch(() => {
        })
    },
    // 日期格式化
    parserDate(date) {
      var t = Date.parse(date)
      if (!isNaN(t)) {
        return new Date(Date.parse(date.replace(/-/g, '/')))
      }
    },
    // 查找日期格式返回
    formatDate: function (date) {
      if (typeof (date) === 'object') {
        var ym
        var y = date.getFullYear()
        var m = date.getMonth() + 1
        var d = date.getDate()
        if (m < 10) {
          m = '0' + m
        }
        if (d < 10) {
          d = '0' + d
        }
        ym = y + '-' + m + '-' + d
        return ym
      } else {
        return date
      }

    },
    //预存列表
    getList() {
      // 查找开始日期
      this.listQuery.minTime = this.alarmdate == null ? null : this.formatDate(this.alarmdate[0]) + '00:00:00'
      // 查找结束日期
      this.listQuery.maxTime = this.alarmdate == null ? null : this.formatDate(this.alarmdate[1]) + '23:59:59'
      tcDailyaccountlist(this.listQuery).then((response) => {
        response.data.data.list.forEach((item) => {
          //预约人
          var fuseuserlist = this.foperatorlist
          for (var i in fuseuserlist) {
            console.log(fuseuserlist[i].value)
            console.log(item.fuseuser)
            if (fuseuserlist[i].value == item.fuseuser) {
              item.fsiteName = fuseuserlist[i].label
            }
          }
        })
        console.log("获取到值", response.data.data.list)
        this.list = response.data.data.list
        this.total = response.data.data.total
        this.listLoading = false
      })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    resetForm() {
      this.dataForm = {
        fbillno: undefined, // 预存单号
        fchargedate: undefined, // 预存日期
        ftaskno: undefined, // 课题组编号
        fteamno: undefined, // 所属团队
        fuseuser: undefined, // 预存人员
        fchargeamt: undefined, // 预存金额
        fexplanation: undefined, // 备注
        foperator: this.$store.state.user.id, // 经办人员
        fupddate: undefined, // 经办时间
        fchargetype: 1, //1存2取
        fstate: 0,//1已确认 0 未确认
      }
      this.tsTaskuserlist = []
      this.fuseuserlist = []
    },
    // 添加
    handleCreate() {
      this.resetForm()
      this.getFbillnos() //单号自动生成
      this.dataForm.fchargedate = new Date()
      this.dataForm.fsiteNo = this.$store.state.user.fsiteNo
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    // 编辑
    edit(row) {
      this.dataForm = JSON.parse(JSON.stringify(row))
      if (row.fstate == '0') {
        this.viewFlag = false
      } else {
        this.viewFlag = true
      }
      //课题组列表
      this.tsTaskuserlists(this.dataForm.fteamno)
      //人员列表
      this.getListAreas(this.dataForm.ftaskno)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    //查找
    handleFilter() {
      this.listQuery.page = 1
      console.log(this.alarmdate)
      // if(this.alarmdate==[]){
      //   this.listQuery.minTime =  undefined
      //   this.listQuery.maxTime =  undefined
      // }else{
      //   this.listQuery.minTime =  moment(this.alarmdate[0]).format("YYYY-MM-DDHH:mm:ss")
      //   this.listQuery.maxTime = moment(this.alarmdate[1]).format("YYYY-MM-DDHH:mm:ss")
      // }
      this.getList()
    },
    //添加
    createData() {
      // if (this.dataForm.fchargedate == "" || this.dataForm.fchargedate == undefined) {
      //   this.$notify.error({
      //     title: '失败',
      //     message: "日期不能为空"
      //   })
      //   return;
      // }
      // if (this.dataForm.fteamno == "" || this.dataForm.fteamno == undefined) {
      //   this.$notify.error({
      //     title: '失败',
      //     message: "团队不能为空"
      //   })
      //   return;
      // }
      // if (this.dataForm.ftaskno == "" || this.dataForm.ftaskno == undefined) {
      //   this.$notify.error({
      //     title: '失败',
      //     message: "课题组不能为空"
      //   })
      //   return;
      // }
      // if (this.dataForm.fuseuser == "" || this.dataForm.fuseuser == undefined) {
      //   this.$notify.error({
      //     title: '失败',
      //     message: "预存人员不能为空"
      //   })
      //   return;
      // }
      // if (this.dataForm.fchargeamt == "" || this.dataForm.fchargeamt == undefined) {
      //   this.$notify.error({
      //     title: '失败',
      //     message: "金额不能为空"
      //   })
      //   return;
      // }
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          console.log("添加")
          var dataForm = JSON.parse(JSON.stringify(this.dataForm))
          dataForm.fsiteNo = this.$store.state.user.fsiteNo
          dataForm.fchargedate = moment(this.dataForm.fchargedate).format("YYYY-MM-DD HH:mm:ss")
          dataForm.fupddate = moment(new Date()).format("YYYY-MM-DD HH:mm:ss")
          console.log(dataForm)
          tcDailyaccountcreate(dataForm)
            .then((response) => {
              this.getList();
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加收费预存成功'
              })
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response
              })
            })
        }})
    },
    //更新
    updateData() {
      console.log("更新")
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          var dataForm = JSON.parse(JSON.stringify(this.dataForm))
          dataForm.fsiteNo = this.$store.state.user.fsiteNo
          dataForm.fchargedate = moment(this.dataForm.fchargedate).format("YYYY-MM-DD HH:mm:ss")
          dataForm.fupddate = moment(new Date()).format("YYYY-MM-DD HH:mm:ss")
          console.log(dataForm)
          tcDailyaccountupdate(dataForm)
            .then((response) => {
              this.getList();
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新收费预存成功'
              })
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response
              })
            })
        }})
    },
    handleDelete(row) {
      this.$confirm('是否作废此单号：' + row.fbillno, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dataForm = Object.assign({}, row)
        cance({fbillno:row.fbillno})
          .then((response) => {
            this.$notify.success({
              title: '成功',
              message: '已作废成功'
            })
            this.getList();
          })
          .catch((response) => {
            this.$notify.error({
              title: '失败',
              message: response
            })
          })
      })
    },
    //收费预存确认
    confirm(row) {
      this.$confirm('是否确认此单号：' + row.fbillno, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dataForm = Object.assign({}, row)
         statusUpdate({datatable:'m_tc_dailyaccount',fbillno:row.fbillno,type:2})
          .then((response) => {
            this.$notify.success({
              title: '成功',
              message: '已确认成功'
            })
            this.getList();
          })
          .catch((response) => {
            this.$notify.error({
              title: '失败',
              message: response
            })
          })
      })
    },
    indexMethod(index) {
      index = index + 1
      return index
    }
  }
}
</script>
